"""
sort, sorted区别，sort是列表中的函数，对列表排序会改变列表，sorted不会。
sorted(iterable, key,reverse)
key: 带参数的函数，用来为每个元素提取比较值
"""
from operator import itemgetter, attrgetter

list1 ='I am LQQ that come from GanSU'.split()

def ChangeLower(strname:str):    #括号里的strname: str什么意思，‘：’是用来声明的吗
    return strname.lower()

list1.sort(key = ChangeLower)
print(list1)

student1 = [
    ('jane', 'B', 12),
    ('john', 'A', 15),
    ('dave', 'B', 10),
]

print(sorted(student1,key = lambda x:x[2]))

class Student(object):
    def __init__(self, name, level,age):
        self.name = name
        self.age = age
        self.level = level

    def __repr__(self):
        return repr((self.name,self.level,self.age))

student = Student('zhang','A',18)

student2 = [
    Student('zhang', 'A', 18),
    Student('li', 'B', 15),
    Student('wang', 'B', 10),
]

print(sorted(student2,key = lambda student : student.age,reverse=True))
print('--'*50)

#operator系列
print(sorted(student1, key = itemgetter(2)))        #第三个元素为依据，升序排序
print(sorted(student2,key = attrgetter('age')))     #age属性升序排序
print('--'*50)
print(sorted(student1,key = itemgetter(1,2)))       #先以第二个元素为依据，后以第三个元素为依据，升序
print(sorted(student1,key = lambda x:(x[1],-x[2])))  #先以第二个元素为依据，升序，后以第三个元素为依据，降序
print(sorted(student2,key = attrgetter('level','age')))   #先以level升序，后以age升序
print('--'*50)

#查看排序稳定性
list3 = [('abc', 1), ('bcd', 1), ('abc', 2), ('bcd', 2)]
print(sorted(list3, key=itemgetter(0)))    #以第一个元素为依据，升序

dict1 = { 'Li' :    ['M',7],
          'Zhang' : ['E',2],
          'Wang'  : ['P',3],
           'Jiang': ['C',2],
           'Qian' : ['C',9],
           'Chen' : ['H',7] }

print(sorted(dict1.items(), key = lambda x:x[1][0]))  #以第二个元素的第一位进行比较

gameresult = [
    { "name":"Bob", "wins":10, "losses":3, "rating":75.00 },
    { "name":"David", "wins":3, "losses":5, "rating":57.00 },
    { "name":"Carol", "wins":4, "losses":5, "rating":57.00 },
    { "name":"Patty", "wins":9, "losses":3, "rating": 71.48 }]

print(sorted(gameresult, key=lambda x:x['rating'], reverse=True))   #以每个列表元素的‘rating’元素为依据，降序
print(sorted(gameresult, key=itemgetter('rating','name')))      ##先以每个列表元素的‘rating’元素为依据,后以每个列表元素的‘name’元素为依据
print('--'*50)

